package Tables;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import Others.TableCellListener;
import Utility.Customer;
import TableAdditions.CustomerTableAddition;
import TableAdditions.CustomerUnitPriceTableAddition;
import Utility.Product;
import TableAdditions.main;
import TableEditions.CustomerUnitPriceTableEdition;

import java.awt.Desktop.Action;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class CustomerUnitPriceTableInterface extends JPanel implements ActionListener  {
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    JButton customerUnitPriceAddButton=new JButton("Yeni");
    JButton customerUnitPriceDeleteButton=new JButton("Sil");
    JButton customerUnitPriceEditButton=new JButton("Düzenle");
    String selectedCustomer="";
    String selectedProduct="";
    float selectedPrice;
    float[] selectedPrices;
    Customer[] customers;
    Product[] products;
    int selectedRow=-1;
    
    final String[] newData=new String[3]; 
    CustomerUnitPriceTableAddition additive;
    CustomerUnitPriceTableEdition edit;
    
    public CustomerUnitPriceTableInterface() {
    	
    	//super(new GridBagLayout());
    	//table.setBounds(0, 0,50,50);
 
        String[] columnNames = {"Müşteri",
                                "Ürün","Birim Fiyat"};
	 	
        

        for(int i=0;i<columnNames.length;i++)
        	model.addColumn(columnNames[i]);	//add columns
        
        
        addNewItem();
        
        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);
        //scrollPane.setBounds(0,0,100, 100);
        addItem(scrollPane, 0, 1, 1, 1, GridBagConstraints.CENTER);
      //Add the scroll pane to this panel.
        add(scrollPane);
      
        
        table.addMouseListener(new MouseAdapter() {
			
			
			@Override
			public void mouseClicked(MouseEvent arg0) {
				// TODO Auto-generated method stub
				 if (table.getColumnSelectionAllowed()
		                    && !table.getRowSelectionAllowed()) {
					  
		                System.out.println("11111111111111");
		                // Column selection is enabled
		                // Get the indices of the selected columns
		                int[] vColIndices = table.getSelectedColumns();
		            } else if (!table.getColumnSelectionAllowed()
		                    && table.getRowSelectionAllowed()) {
		            	// System.out.println("222222222222");
		            	 selectedRow=table.getSelectedRow(); 
		            	 
		            	 if(selectedRow>-1){
		            		 selectedCustomer=customers[selectedRow].getCustomerName();
		            		 selectedProduct=products[selectedRow].getProductName();
		            		 selectedPrice=selectedPrices[selectedRow];
		            		 System.out.println("selectedCustomer= "+selectedCustomer+"	"+"selectedProduct= "+selectedProduct+
		            				 "	selectedPrice= "+selectedPrice);
		            	 }
		            	 //System.out.println("selectedCustomer= "+customerNames[selectedRow]);
		                // Row selection is enabled
		                // Get the indices of the selected rows
		                int[] rowIndices = table.getSelectedRows();
		            } else if (table.getCellSelectionEnabled()) {
		                // Individual cell selection is enabled
		            	System.out.println("333333333333");

		                // In SINGLE_SELECTION mode, the selected cell can be retrieved using
		            	table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		                int rowIndex = table.getSelectedRow();
		                int colIndex = table.getSelectedColumn();
		              

		                // In the other modes, the set of selected cells can be retrieved using
		                table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		                table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

		                // Get the min and max ranges of selected cells
		                int rowIndexStart = table.getSelectedRow();
		                int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
		                int colIndexStart = table.getSelectedColumn();
		                int colIndexEnd = table.getColumnModel().getSelectionModel()
		                    .getMaxSelectionIndex();

		                // Check each cell in the range
		                for (int r=rowIndexStart; r<=rowIndexEnd; r++) {
		                    for (int c=colIndexStart; c<=colIndexEnd; c++) {
		                        if (table.isCellSelected(r, c)) {
		                        	System.out.println("4444444444444");
		                            // cell is selected
		                        }
		                    }
		                }
		            }
				
			}
		});
        
        
        
        AbstractAction action = new AbstractAction()
        {
            public void actionPerformed(ActionEvent e)
            {
                TableCellListener tcl = (TableCellListener)e.getSource();
                System.out.println("Row   : " + tcl.getRow());
                System.out.println("Column: " + tcl.getColumn());
                System.out.println("Old   : " + tcl.getOldValue());
                System.out.println("New   : " + tcl.getNewValue());
                String sp=(String) tcl.getNewValue();
                selectedPrice=Float.parseFloat(sp);
            }
        };

        
        TableCellListener tcl = new TableCellListener(table, action);    
            
            
        
        customerUnitPriceAddButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				additive=new CustomerUnitPriceTableAddition(CustomerUnitPriceTableInterface.this);

				
			}
			
			
		});
        
        
        
        
        customerUnitPriceDeleteButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				//additive=new CustomerUnitPriceTableAddition(CustomerUnitPriceTableInterface.this);
				if(selectedRow!=-1){
					System.out.println("Delete special price");
					
					Connection con = null;
			        Statement st = null;
			        ResultSet rs = null;

			        String url = "jdbc:mysql://localhost:3306/mydb";
			        String user = "root";
			        String password = "qweasdzxc";
			        Object[][] mydata=null;
			        try {
			            con = (Connection) DriverManager.getConnection(url, user, password);
			            st = (Statement) con.createStatement();
			            st.executeUpdate("DELETE from special_price WHERE special_price_customer_id='"+customers[selectedRow].getCustomerId()+"'" +
			            		"and special_price_product_id='"+products[selectedRow].getProductId()+"' ");
			            addNewItem();
			            con.close();
			        } catch (SQLException ex) {
			            Logger lgr = Logger.getLogger(main.class.getName());
			            lgr.log(Level.SEVERE, ex.getMessage(), ex);

			        } finally {
			            try {
			                if (rs != null) {
			                    rs.close();
			                }
			                if (st != null) {
			                    st.close();
			                }
			                if (con != null) {
			                    con.close();
			                }

			            } catch (SQLException ex) {
			                Logger lgr = Logger.getLogger(main.class.getName());
			                lgr.log(Level.WARNING, ex.getMessage(), ex);
			            }
			        }
					/////////////////////////////////////////
				}
				
			}
			
			
		});
        
        
        customerUnitPriceEditButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if(selectedRow!=-1){
					edit=new CustomerUnitPriceTableEdition(CustomerUnitPriceTableInterface.this
							,products[selectedRow],customers[selectedRow]);
				}
				
			}
			
			
		});
        
        
        addItem(customerUnitPriceAddButton,0,2,1,1,GridBagConstraints.CENTER);//call the addItem method and add in panel
        addItem(customerUnitPriceDeleteButton,1,2,1,1,GridBagConstraints.CENTER);//call the addItem method and add in panel
        addItem(customerUnitPriceEditButton,2,2,1,1,GridBagConstraints.CENTER);//call the addItem method and add in panel
        
        
       
       
    }
    public void addNewItem(){
    	deleteAllRows(model);
    	
    	Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        String url = "jdbc:mysql://localhost:3306/mydb";
        String user = "root";
        String password = "qweasdzxc";
        Object[][] mydata=null;
        try {
            con = (Connection) DriverManager.getConnection(url, user, password);
            st = (Statement) con.createStatement();
            rs=st.executeQuery("SELECT * from special_price order by special_price_customer_id");
            int i=0,counter=0;
            while(rs.next())
            	++counter;
            
            if(counter>0){
            System.out.println("special pricecounter= "+counter);
            rs.first();
            System.out.println("special price counter= "+counter);
            mydata=new Object[counter][3];
            mydata[i][0]=rs.getString("special_price_customer_id");
    		mydata[i][1]=rs.getString("special_price_product_id");
    		mydata[i][2]=rs.getFloat("special_price");
    		++i;
            while(rs.next())
            {
            		mydata[i][0]=rs.getString("special_price_customer_id");
            		mydata[i][1]=rs.getString("special_price_product_id");
            		mydata[i][2]=rs.getFloat("special_price");
            		++i;
        
            }
             
            int row=i;
            selectedPrices= new float[row];
            
            for(int n=0;n<row;n++){
            	selectedPrices[n]=(Float) mydata[n][2];
            }
            
            
            
            i=0;
            customers=new Customer[row];
            
            for(i=0;i<row;i++){
            	rs=st.executeQuery("SELECT * from customer where customer_id='"+mydata[i][0]+"'");
            	rs.next();
            	customers[i]=new Customer();
            	customers[i].setCustomerName(rs.getString("customer_name"));
            	customers[i].setCustomerId(rs.getInt("customer_id"));
            	mydata[i][0]=rs.getString("customer_name");
            }
         
            products=new Product[row];
            for(i=0;i<row;i++){
            	rs=st.executeQuery("SELECT * from product where product_id='"+mydata[i][1]+"'");
            	rs.next();
            	products[i]=new Product();
            	products[i].setProductName(rs.getString("product_name"));
            	products[i].setProductId(rs.getInt("product_id"));
            	mydata[i][1]=rs.getString("product_name");
            }
            
            
            table.setPreferredScrollableViewportSize(new Dimension(900, 600));
            table.setFillsViewportHeight(true);
            for(int j=0;j<mydata.length;j++)
            	model.addRow(mydata[j]);
            
            }
            
           con.close();
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(main.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(main.class.getName());
                lgr.log(Level.WARNING, ex.getMessage(), ex);
            }
        }
	
  
 
    	
    	
  		
      }
    
    public static void deleteAllRows(final DefaultTableModel model) {
	    for( int i = model.getRowCount() - 1; i >= 0; i-- ) {
	        model.removeRow(i);
	    }
	}
      
    
    /**
     * This method Add new row to the table
     */
    private void addTableByRow(Object[] yeni){
    	model.addRow(yeni);
   
    }

    /**
     *This method is good to use GridBagLayout simple
     * 
     */
    private void addItem(JComponent c, int x, int y, int width, int height, int align) {
        GridBagConstraints gc = new GridBagConstraints();
        gc.gridx = x;
        gc.gridy = y;
        gc.gridwidth = width;
        gc.gridheight = height;
        gc.weightx = 100.0;
        gc.weighty = 100.0;
        gc.insets = new Insets(5, 5, 5, 5);
        gc.anchor = align;
        gc.fill = GridBagConstraints.NONE;
        add(c, gc);
      }
	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		
	}
}




